<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="role-list-container">
    <!-- 搜索区 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="状态" style="min-width: 180px;">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchRoles">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-button type="primary" @click="addRole"><i class="el-icon-plus"></i>新增角色</el-button>
      </el-form>
    </el-card>

    <!-- 列表区 -->
    <el-card class="list-card">
      <el-table :data="roleList" border stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="roleName" label="角色名称" width="130" />
        <el-table-column label="角色图标">
          <template #default="scope">
            <el-image
              v-if="scope.row.roleLogo"
              :src="scope.row.roleLogo"
              style="width: 40px; height: 40px; border-radius: 4px"
              fit="cover"
            />
            <div v-else style="width: 40px; height: 40px; border-radius: 4px; background: #eee; display: flex; align-items: center; justify-content: center;">
              <i class="el-icon-user"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="roleDes" label="角色描述" />
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色权限" width="300">
          <template #default="scope">
            <div v-if="scope.row.permissions && scope.row.permissions.length > 0">
              <el-tag
                v-for="permission in scope.row.permissions"
                :key="permission.id"
                style="margin: 2px;"
              >
                {{ permission.permissionName }}
              </el-tag>
            </div>
            <div v-else>
              <el-tag type="info">无权限</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="pageNum"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next, total"
        />
      </div>
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="formVisible"
      title="角色表单"
      :width="600"
      :close-on-click-modal="false"
    >
      <RoleForm :model-value="currentRole" @save="handleSave" @cancel="cancel" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getRoles, deleteRole, unassignRolePermissions } from '@/api/permission'
import RoleForm from './RoleForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const roleList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const formVisible = ref(false)
const currentRole = ref({})

const searchForm = ref({
  roleName: '',
  status: ''
})

// 获取角色列表
const fetchRoles = async () => {
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...(searchForm.value.roleName && { roleName: searchForm.value.roleName }),
      ...(searchForm.value.status !== '' && { status: searchForm.value.status })
    }

    const response = await getRoles(params)

    const roleMap = new Map()

    response.data.records.forEach(item => {
      const roleId = item.id

      if (!roleMap.has(roleId)) {
        roleMap.set(roleId, {
          roleId: roleId,
          roleName: item.roleName,
          roleLogo: item.roleLogo || '',
          roleDes: item.roleDes || '',
          status: item.status ?? 1,
          permissions: []
        })
      }

      if (item.permissions && item.permissions.length > 0) {
        item.permissions.forEach(permission => {
          roleMap.get(roleId).permissions.push({
            id: permission.id,
            permissionName: permission.permissionName
          })
        })
      }
    })

    roleList.value = Array.from(roleMap.values())
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error(error)
  }
}

onMounted(() => {
  fetchRoles()
})

const handlePageChange = (page) => {
  pageNum.value = page
  fetchRoles()
}

const addRole = () => {
  currentRole.value = {}
  formVisible.value = true
}

const handleEdit = (row) => {
  currentRole.value = { ...row }
  formVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该角色吗？删除前会先解除该角色的所有权限绑定。',
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await unassignRolePermissions({
      roleId: row.roleId,
      permissionIds: row.permissions.map(p => p.id)
    })

    await deleteRole(row.roleId)

    ElMessage.success('角色删除成功')
    fetchRoles()
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('删除失败')
    console.error(error)
  }
}

const handleSave = () => {
  formVisible.value = false
  fetchRoles()
}

const cancel = () => {
  formVisible.value = false
}

// 重置搜索条件
const handleReset = () => {
  searchForm.value.roleName = ''
  searchForm.value.status = ''
  pageNum.value = 1
  fetchRoles()
}
</script>

<style scoped>
.list-card {
  background-color: #fff;
}
.role-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  width: 100%;
}
.pagination-container {
  margin-top: 15px;
  text-align: right;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
